package com.jams.goodox.activity.serve.tenement;

import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.jams.goodox.BasePayActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.serve.ChooseBillManager;
import com.jams.goodox.adapter.PayTypeAdapter;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.constant.UamaPayCode;
import com.jams.goodox.entity.StringBean;
import com.jams.goodox.entity.TenementPayOrderBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.pay.AiliPayBean;
import com.jams.goodox.entity.pay.BalancePayBean;
import com.jams.goodox.entity.pay.WeChatPayBean;
import com.jams.goodox.listen.PayListener;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.ProgressDialogUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TipAlertDialog;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.ChooseBillView;
import com.jams.goodox.widget.NoScrollListView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;
import com.jams.library.widget.MyListView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 物业缴费支付页
 * Created by jams_zhen on 2016/9/24.
 */

public class TenementPayActivity extends BasePayActivity {
    @Bind(R.id.tx_orderNum)
    TextView txOrderNum;
    @Bind(R.id.lst)
    NoScrollListView lst;
    @Bind(R.id.tx_payMoney)
    TextView txPayMoney;
    @Bind(R.id.lv_pay_type)
    MyListView lvPayType;
    @Bind(R.id.choose_bill_view)
    ChooseBillView chooseBillView;

    private String invoiceType = "0";

    private ListCommonAdapter monthAdapter;

    private TenementPayOrderBean.DataBean dataBean;

    private DecimalFormat decimalFormat;

    private PayTypeAdapter adapter;

    private String orderNo;

    private List<Integer> payTypeList;
    private String busId;

    //余额
    private double balance;
    private double totalPrice;//应付金额or总金额

    // 只在页面第一次加载的时候去设置按钮选中状态
    private boolean isFirstInitSelect = true;

    private User user;

    private ChooseBillManager chooseBillManager;

    @Override
    protected int getLayoutId() {
        return R.layout.tenement_pay_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "选择付款方式");

        getDate();
        if (dataBean == null || dataBean.getPayItem() == null) {
            ToastUtil.showShort(this, "支付参数有误");
            return;
        }
        setDate();
        ListCommonAdapter itemAdapter = new ListCommonAdapter<TenementPayOrderBean.DataBean.PayItemBean>(this, dataBean.getPayItem(), R.layout.item_tenement_pay) {
            @Override
            public void convert(ListCommonViewHolder helper, final TenementPayOrderBean.DataBean.PayItemBean item, int position) {
                TextView tx_type = helper.getView(R.id.tx_type);
                TextView tx_address = helper.getView(R.id.tx_address);
                NoScrollListView lst_average = helper.getView(R.id.lst_average);
                tx_type.setText(item.getItem());
                tx_address.setText(item.getAddress());
                monthAdapter = new ListCommonAdapter<TenementPayOrderBean.DataBean.PayItemBean.MonthListBean>(TenementPayActivity.this, item.getMonthList(), R.layout.item_month_pay) {
                    @Override
                    public void convert(ListCommonViewHolder helper, TenementPayOrderBean.DataBean.PayItemBean.MonthListBean item, int position) {
                        TextView tx_month = helper.getView(R.id.tx_month);
                        TextView tx_price = helper.getView(R.id.tx_price);
                        tx_month.setText(item.getBillYear() + "年" + item.getBillMonth() + "月");
                        tx_price.setText(getResources().getString(R.string.rmb) + decimalFormat.format(item.getTotalPrice()));
                    }
                };
                lst_average.setAdapter(monthAdapter);
            }
        };
        lst.setAdapter(itemAdapter);

        lvPayType.setAdapter(adapter = new PayTypeAdapter(this, payTypeList));
        adapter.setNeedPayMoney(totalPrice);
        txOrderNum.setFocusable(true);
        txOrderNum.setFocusableInTouchMode(true);
        txOrderNum.requestFocus();
        chooseBillManager = new ChooseBillManager(this, true, busId, chooseBillView);
    }

    /**
     * 获取缴费传递参数
     */
    private void getDate() {
        dataBean = (TenementPayOrderBean.DataBean) getIntent().getSerializableExtra("bean");
        totalPrice = dataBean.getTotalPrice();
        busId = getIntent().getStringExtra("busId");
    }

    /**
     * t填写页面信息
     */
    private void setDate() {
        txOrderNum.setText("付款单号：" + dataBean.getOrderNo());
        orderNo = dataBean.getOrderNo();
        decimalFormat = new DecimalFormat("#0.00");
        txPayMoney.setText(Html.fromHtml("<font color=#666666>" + "待缴金额：" + "</font>"
                + "<b><font color=#fa5757>" + getResources().getString(R.string.rmb) + decimalFormat.format(dataBean.getTotalPrice()) + "</font></b>"));

        //设置支付类型
        payTypeList = dataBean.getPayType();
        if (payTypeList == null)
            payTypeList = new ArrayList<>();
        payTypeList.add(0, -99);
        user = DataCacheManager.getInstance().getUser();
        // 绑定微信支付回调
        bindWXResultBroadcast();
    }

    @OnClick({R.id.tx_surePay})
    public void onClick(View view) {
        if (Utils.isFastDoubleClick())
            return;
        switch (view.getId()) {
            case R.id.tx_surePay:
                if (adapter.getPayType() == -1 || payTypeList.size() == 0) {
                    ToastUtil.showShort(this, "请选择一种支付方式");
                    return;
                }
                if (chooseBillManager != null && !"0".equalsIgnoreCase(chooseBillManager.getInvoiceType()))
                    invoiceType = chooseBillManager.getInvoiceType();
                else invoiceType = "0";
                if (!TextUtils.isEmpty(invoiceType) && !"0".equalsIgnoreCase(invoiceType)) {
                    commitBill();
                } else {
                    ProgressDialogUtils.show(this);
                    goPay();
                }
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        requestBalance();
    }

    /**
     * 请求最新余额数据
     */
    public void requestBalance() {
        enqueue(createCallService(MineService.class).balance(user.getEnterpriseAdminId()), new RetrofitCallbackListener<StringBean>() {
            @Override
            public void onSuccess(Call<StringBean> call, StringBean result) {
                try {
                    balance = Double.parseDouble(result.getData());
                } catch (NumberFormatException e) {
                    balance = 0.00;
                }
                adapter.setBalance(balance);
                adapter.notifyDataSetChanged();
                // 初始化支付按钮选中项
                initSelected();
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    /**
     * 初始化支付按钮选中项
     */
    private void initSelected() {
        if (isFirstInitSelect) {
            isFirstInitSelect = false;
            if (balance >= totalPrice) {
                // 余额大于等于订单实付金额,选择余额支付
                adapter.setSelectionPosition(0);
            } else {
                if (payTypeList.size() >= 2) {
                    adapter.setSelectionPosition(1);
                }
            }
        }
    }

    /**
     * 提交发票
     */
    private void commitBill() {
        Map<String, Object> map = new HashMap<>();
        map.put("invoiceType", invoiceType);
        map.put("invoiceName", chooseBillManager.getInvoiceName());
        map.put("payNo", orderNo);
        map.put("userId", DataCacheManager.getInstance().getUser().getEnterpriseAdminId());
        ProgressDialogUtils.show(this);
        enqueue(createCallService(ServiceService.class).commitBill(map), new RetrofitCallbackListener<StringBean>() {
            @Override
            public void onSuccess(Call<StringBean> call, StringBean tenementMonthBean) {
                goPay();
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
                ProgressDialogUtils.dismiss();
            }
        });
    }

    //支付成功
    protected void paySuccess() {
        ToastUtil.show("支付成功");
        Intent intent = new Intent(this, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }


    /**
     * 选择支付
     */
    private void goPay() {
        switch (adapter.getPayType()) {//支付方式选择 -99余额支付 0:支付宝    1:银联  2:微信  5;线下支付
            case 0://支付宝支付
                AiliPayBean ailiPayBean = new AiliPayBean();
                ailiPayBean.setId(orderNo);
                ailiPayBean.setCode(orderNo);
                ailiPayBean.setType(Constants.PayType.Type_WYJF);
                ailiPayBean.setTitle("物业缴费");
                ailiPayBean.setMoneyCharge(StringUtils.doubleToString(dataBean.getTotalPrice()));
                payByAili(ailiPayBean, new PayListener() {
                    @Override
                    public void payResult(final int status, final String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ProgressDialogUtils.dismiss();
                                switch (status) {
                                    case UamaPayCode.PAY_SUCCESS:
                                        paySuccess();
                                        break;
                                }
                            }
                        });
                    }
                });
                break;
            case 2:
                //微信支付
                WeChatPayBean weChatPayBean = new WeChatPayBean();
                weChatPayBean.setOrderId(orderNo);
                weChatPayBean.setPayType(Constants.PayType.Type_WYJF);
                payByWeChat(weChatPayBean, new PayListener() {
                    @Override
                    public void payResult(int status, String msg) {
                        ProgressDialogUtils.dismiss();
                        switch (status) {
                            case UamaPayCode.PAY_SUCCESS:
                                paySuccess();
                                break;
                        }
                    }
                });
                break;
            case -99:
                // 单选余额支付
                ProgressDialogUtils.dismiss();
                if (balance < dataBean.getTotalPrice()) {
                    //余额不够支付应付款
                    ToastUtil.show(this, R.string.scan_pay_balance_less);
                } else {
                    //余额足够支付应付款
                    BalancePayBean balancePayBean = new BalancePayBean();
                    balancePayBean.setType(2);
                    balancePayBean.setUserId(user.getEnterpriseAdminId());
                    balancePayBean.setBalance(StringUtils.doubleToString(balance));
                    balancePayBean.setOrderId(orderNo);
                    balancePayBean.setPaySubCode(StringUtils.toString(Constants.TENEMENT_PAY_CODE));
                    payByBalance(balancePayBean, new PayListener() {
                        @Override
                        public void payResult(int status, String msg) {
                            switch (status) {
                                case UamaPayCode.PAY_SUCCESS:
                                    paySuccess();
                                    break;
                                case UamaPayCode.BALANCE_CHANGE:
                                    ToastUtil.show(msg);
                                    TipAlertDialog.showTip(TenementPayActivity.this, null, msg, new SuccessListener() {
                                        @Override
                                        public void success() {
                                            requestBalance();
                                        }
                                    });
                                    break;
                                case UamaPayCode.PAY_ERROR:
                                    ToastUtil.show(msg);
                                    TipAlertDialog.showTip(TenementPayActivity.this, null, msg);
                                    break;
                            }
                        }
                    });
                }
                break;
        }

    }

}
